package com.dmap.admin.service.backgroundv2.impl;

import com.dmap.admin.constants.AdminConstant;
import com.dmap.admin.controller.backgroundv2.param.UserV2Param;
import com.dmap.admin.controller.backgroundv2.param.UserV2SelectParam;
import com.dmap.admin.dao.UserMapper;
import com.dmap.admin.po.User;
import com.dmap.admin.po.UserExample;
import com.dmap.admin.service.backgroundv2.UserV2Service;
import com.dmap.base.units.MD5Util;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * \* User: helei
 * \* Date: 04/05/18
 * \* Description:用户相关接口实现类
 * \
 */
@Service
public class UserV2ServiceImpl implements UserV2Service {

    @Resource
    private UserMapper userMapper;

    @Override
    public User insertUser(UserV2Param param) {
        User user = new User();
        user.setAccount(param.getAccount());
        user.setName(param.getName());
        user.setNickname(param.getNickname());
        if (StringUtils.isNotEmpty(param.getPassword())) {
            user.setPassword(MD5Util.md5Password(param.getPassword()));
        }
        user.setHandphone(param.getHandphone());
        user.setEmail(param.getEmail());
        user.setSex(param.getSex());
        user.setBirthday(param.getBirthday());
        user.setProvince(param.getProvince());
        user.setCity(param.getCity());
        user.setPosition(param.getPosition());
        if (StringUtils.isNotBlank(param.getCompanyId()) && StringUtils.isNumeric(param.getCompanyId())) {
            user.setCompanyId(Long.valueOf(param.getCompanyId()));
        }
        user.setCompanyName(param.getCompanyName());
        user.setCompanyType(param.getCompanyType());
        if (StringUtils.isNotBlank(param.getCreatorId()) && StringUtils.isNumeric(param.getCreatorId())) {
            user.setCreatorId(Long.valueOf(param.getCreatorId()));
            user.setEditorId(user.getCreatorId());
        }
        user.setCreatorAccount(param.getCreatorAccount());
        user.setEditorAccount(user.getCreatorAccount());
        if (StringUtils.isNotBlank(param.getDepartmentId()) && StringUtils.isNumeric(param.getDepartmentId())) {
            user.setDepartmentId(Long.valueOf(param.getDepartmentId()));
        }
        user.setDepartmentName(param.getDepartmentName());
        user.setHeadImageUrl(param.getHeadImageUrl());
        user.setStatus(param.getStatus());
        user.setLoginWrongNum(0);
        user.setUserType(param.getUserType());
        user.setDeleteStatus(AdminConstant.DELETE_STATUS_NORMAL);
        user.setCreateTime(System.currentTimeMillis() / 1000);
        user.setUpdateTime(user.getCreateTime());
        int success = userMapper.insertSelective(user);
        return (success == 1) ? user : null;
    }


    @Override
    public boolean updateUser(UserV2Param param) {
        User user = new User();
        user.setId(Long.valueOf(param.getId()));
        user.setAccount(param.getAccount());
        user.setName(param.getName());
        user.setNickname(param.getNickname());
        if (StringUtils.isNotEmpty(param.getPassword())) {
            user.setPassword(MD5Util.md5Password(param.getPassword()));
        }
        user.setHandphone(param.getHandphone());
        user.setEmail(param.getEmail());
        user.setSex(param.getSex());
        user.setBirthday(param.getBirthday());
        user.setProvince(param.getProvince());
        user.setCity(param.getCity());
        user.setPosition(param.getPosition());
        if (StringUtils.isNotBlank(param.getCompanyId()) && StringUtils.isNumeric(param.getCompanyId())) {
            user.setCompanyId(Long.valueOf(param.getCompanyId()));
        }
        user.setCompanyName(param.getCompanyName());
        user.setCompanyType(param.getCompanyType());
        if (StringUtils.isNotBlank(param.getEditorId()) && StringUtils.isNumeric(param.getEditorId())) {
            user.setEditorId(Long.valueOf(param.getEditorId()));
        }
        user.setEditorAccount(param.getEditorAccount());
        if (StringUtils.isNotBlank(param.getDepartmentId()) && StringUtils.isNumeric(param.getDepartmentId())) {
            user.setDepartmentId(Long.valueOf(param.getDepartmentId()));
        }
        user.setDepartmentName(param.getDepartmentName());
        user.setHeadImageUrl(param.getHeadImageUrl());
        user.setStatus(param.getStatus());
        user.setDeleteStatus(param.getDeleteStatus());
        user.setLoginWrongNum(param.getLoginWrongNum());
        user.setUserType(param.getUserType());
        user.setUpdateTime(System.currentTimeMillis() / 1000);
        return userMapper.updateByPrimaryKeySelective(user) == 1;
    }

    @Override
    public boolean deleteByIdList(List<Long> idList) {
        User user = new User();
        user.setStatus(AdminConstant.FORBID_STATUS);
        user.setDeleteStatus(AdminConstant.DELETE_STATUS_DELETED);
        user.setCompanyId(0L);
        UserExample example = new UserExample();
        example.createCriteria().andIdIn(idList);
        int success = userMapper.updateByExampleSelective(user, example);
        return success >= 1;
    }

    @Override
    public User selectById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public User validateAccountOrHandphoneIsExist(String account, String handphone) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria1 = example.createCriteria();
        UserExample.Criteria criteria2 = example.createCriteria();
        if (StringUtils.isNotBlank(account)) {
            criteria1.andAccountEqualTo(account);
        }
        if (StringUtils.isNotBlank(handphone)) {
            criteria2.andHandphoneEqualTo(handphone);
        }
        example.or(criteria2);
        List<User> list = userMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public User selectByLoginV2Param(String account, String handphone) {
        UserExample example = new UserExample();
        //匹配 用户账号 进行查询
        UserExample.Criteria criteria1 = example.createCriteria();
        //匹配 用户手机号 进行查询
        UserExample.Criteria criteria2 = example.createCriteria();
        if (StringUtils.isNotBlank(account)) {
            criteria1.andAccountEqualTo(account);
            criteria1.andDeleteStatusEqualTo(AdminConstant.DELETE_STATUS_NORMAL);
        }
        if (StringUtils.isNotBlank(handphone)) {
            criteria2.andHandphoneEqualTo(handphone);
            criteria2.andDeleteStatusEqualTo(AdminConstant.DELETE_STATUS_NORMAL);
        }
        example.or(criteria2);
        List<User> list = userMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public User selectByAccountOrHandphone(String param) {
        UserExample example = new UserExample();
        //匹配 用户账号 进行查询
        UserExample.Criteria criteria1 = example.createCriteria();
        //匹配 用户手机号 进行查询
        UserExample.Criteria criteria2 = example.createCriteria();
        if (StringUtils.isNotBlank(param)) {
            criteria1.andAccountEqualTo(param);
            criteria2.andHandphoneEqualTo(param);
        }
        example.or(criteria2);
        List<User> list = userMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public int countByDepartmentId(Long departmentId) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andDepartmentIdEqualTo(departmentId);
        criteria.andDeleteStatusEqualTo(AdminConstant.DELETE_STATUS_NORMAL);
        return userMapper.countByExample(example);
    }

    @Override
    public List<User> selectByUserV2SelectParam(UserV2SelectParam param) {
        UserExample example = this.getUserV2SelectParamExample(param);
        //根据前端所传参数不同生成对应的orderBy子句
        String orderByClause = AdminConstant.getOrderByClauseMap().getOrDefault(param.getSortField(), AdminConstant.CREATE_TIME)
                + AdminConstant.getOrderByClauseSequenceMap().getOrDefault(param.getOrder(), AdminConstant.DESC);
        example.setOrderByClause(orderByClause);
        example.setLimitStart((param.getPageIndex() - 1) * param.getPageSize());
        example.setLimitEnd(param.getPageSize());
        return userMapper.selectByExample(example);
    }

    @Override
    public int countByUserV2SelectParam(UserV2SelectParam param) {
        UserExample example = this.getUserV2SelectParamExample(param);
        return userMapper.countByExample(example);
    }

    private UserExample getUserV2SelectParamExample(UserV2SelectParam param) {
        UserExample example = new UserExample();
        //根据 用户账号 模糊搜索
        UserExample.Criteria criteria1 = example.createCriteria();
        //根据 用户名称 模糊搜索
        UserExample.Criteria criteria2 = example.createCriteria();
        //根据 用户手机号 模糊搜索
        UserExample.Criteria criteria3 = example.createCriteria();
        //根据 用户邮箱 模糊搜索
        UserExample.Criteria criteria4 = example.createCriteria();
        //根据 编辑员 模糊搜索
        UserExample.Criteria criteria5 = example.createCriteria();

        criteria1.andCompanyIdEqualTo(Long.valueOf(param.getCompanyId()));
        criteria2.andCompanyIdEqualTo(Long.valueOf(param.getCompanyId()));
        criteria3.andCompanyIdEqualTo(Long.valueOf(param.getCompanyId()));
        criteria4.andCompanyIdEqualTo(Long.valueOf(param.getCompanyId()));
        criteria5.andCompanyIdEqualTo(Long.valueOf(param.getCompanyId()));
        criteria1.andDeleteStatusEqualTo(AdminConstant.DELETE_STATUS_NORMAL);
        criteria2.andDeleteStatusEqualTo(AdminConstant.DELETE_STATUS_NORMAL);
        criteria3.andDeleteStatusEqualTo(AdminConstant.DELETE_STATUS_NORMAL);
        criteria4.andDeleteStatusEqualTo(AdminConstant.DELETE_STATUS_NORMAL);
        criteria5.andDeleteStatusEqualTo(AdminConstant.DELETE_STATUS_NORMAL);
        //如果用户类型为公司管理员， 并且 searchDepartmentId 字段不为空， 则匹配 departmentId 进行查询
        if (param.getUserType() == AdminConstant.USER_TYPE_COMPANY_ADMIN && StringUtils.isNotBlank(param.getSearchDepartmentId())
                && StringUtils.isNumeric(param.getSearchDepartmentId()) && !Long.valueOf(param.getSearchDepartmentId()).equals(0L)) {
            criteria1.andDepartmentIdEqualTo(Long.valueOf(param.getSearchDepartmentId()));
            criteria2.andDepartmentIdEqualTo(Long.valueOf(param.getSearchDepartmentId()));
            criteria3.andDepartmentIdEqualTo(Long.valueOf(param.getSearchDepartmentId()));
            criteria4.andDepartmentIdEqualTo(Long.valueOf(param.getSearchDepartmentId()));
            criteria5.andDepartmentIdEqualTo(Long.valueOf(param.getSearchDepartmentId()));
        }
        //如果用户类型为部门管理员， 并且 departmentId 字段不为空， 则匹配 departmentId 进行查询
        if (param.getUserType() == AdminConstant.USER_TYPE_DEPARTMENT_ADMIN && StringUtils.isNotBlank(param.getDepartmentId())
                && StringUtils.isNumeric(param.getDepartmentId()) && !Long.valueOf(param.getDepartmentId()).equals(0L)) {
            criteria1.andDepartmentIdEqualTo(Long.valueOf(param.getDepartmentId()));
            criteria2.andDepartmentIdEqualTo(Long.valueOf(param.getDepartmentId()));
            criteria3.andDepartmentIdEqualTo(Long.valueOf(param.getDepartmentId()));
            criteria4.andDepartmentIdEqualTo(Long.valueOf(param.getDepartmentId()));
            criteria5.andDepartmentIdEqualTo(Long.valueOf(param.getDepartmentId()));
        }
        if (StringUtils.isNotBlank(param.getSearchKeyword())) {
            criteria1.andAccountLike("%" + param.getSearchKeyword() + "%");
            criteria2.andNameLike("%" + param.getSearchKeyword() + "%");
            criteria3.andHandphoneLike("%" + param.getSearchKeyword() + "%");
            criteria4.andEmailLike("%" + param.getSearchKeyword() + "%");
            criteria5.andEditorAccountLike("%" + param.getSearchKeyword() + "%");
        }
        example.or(criteria2);
        example.or(criteria3);
        example.or(criteria4);
        example.or(criteria5);
        return example;
    }

    @Override
    public int setAllUserLoginWrongNumZero() {
        User user = new User();
        user.setLoginWrongNum(0);
        UserExample example = new UserExample();
        example.createCriteria().andIdGreaterThan(0L);
        return userMapper.updateByExampleSelective(user, example);
    }

}